<template>
  <div class="app-container">

    <!-- 主页 -->
    <div v-show="!detailedPageVisible">

      <!-- 条件搜索 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品ID" prop="id">
          <el-input
            v-model="queryParams.id"
            placeholder="请输入产品ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属品类" prop="categoryId">
          <tree-select
            style="width: 215px"
            :show-count="true"
            v-model="queryParams.categoryId"
            :options="categoryOptions"
            :normalizer="normalizer"
            placeholder="请选择所属品类"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
            <el-option
              v-for="dict in dict.type.iot_product_device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="publishState">
          <el-select v-model="queryParams.publishState" placeholder="请选择发布状态" clearable>
            <el-option
              v-for="dict in dict.type.iot_publish_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 新增、修改、删除、导出功能按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['iot:product:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['iot:product:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['iot:product:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="resetQuery"></right-toolbar>
      </el-row>

      <!-- 产品列表 -->
      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" type="index" align="center" />
        <el-table-column label="图标" align="center" prop="url">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.photoUrl"
              style="width: 30px; height: 30px"
              :src="scope.row.photoUrl"
              :preview-src-list="[scope.row.photoUrl]"
            >
          </el-image>
            <p v-else>暂无</p>
          </template>
        </el-table-column>
        <el-table-column label="产品ID" align="center" prop="id" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="所属品类" align="center" prop="category.categoryName" />
        <el-table-column label="消息协议" align="center" prop="protocolId" />
        <el-table-column label="传输协议" align="center" prop="transportProtocol" />
        <el-table-column label="设备类型" align="center" prop="deviceType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_product_device_type" :value="scope.row.deviceType"/>
          </template>
        </el-table-column>

        <el-table-column label="发布状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.publishState"
              :active-value=1
              :inactive-value=0
              @change="handlePublishStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="产品描述" align="center" prop="description" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetails(scope.row)"
              v-hasPermi="['iot:product:list']"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['iot:product:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['iot:product:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    </div>

    <!-- 添加或修改产品对话框 -->
    <product-add-edit ref="productAddEdit" />

    <!-- 详情页 -->
    <product-detailed />

  </div>
</template>

<script>
import { listProduct, delProduct, deployProduct, undeployProduct, getProduct } from '@/api/iot/product'
import ProductDetailed from "./productDetailed";
import ProductAddEdit from "./productAddEdit";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { mapState } from 'vuex'
import { listCategory } from '@/api/iot/category'
import TreeSelect from "@riophae/vue-treeselect";

export default {
  name: "Product",
  components: {
    ProductDetailed,
    ProductAddEdit,
    TreeSelect
  },
  dicts: ['iot_product_device_type', 'iot_publish_state'],
  data() {

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 品类树选项
      categoryOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        productName: null,
        categoryId: null,
        deviceType: null,
      }
    };
  },
  computed: {
    ...mapState({
      detailedPageVisible: state => state.product.detailedPageVisible,
      productData: state => state.product.productData
    }),
    routeValue() { return this.$route.query }
  },
  watch: {
    productData() {
      this.getList();
    },
    routeValue: {
      immediate:true,
      handler(params) {
        const productId = params.id;
        if (productId) {
          getProduct(productId).then(({ data }) => {
            this.$store.commit("PRODUCT_DATA", data);
          })
          this.$store.commit("PRODUCT_DETAILED_PAGE_VISIBLE", true);
        }
      }
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  destroyed() {
    // 销毁页面的时候还原数据
    this.$store.commit("PRODUCT_DETAILED_PAGE_VISIBLE", false);
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 发布状态修改 */
    handlePublishStateChange(row) {
      let text = row.publishState === 1 ? "发布" : "取消发布";
      this.$modal.confirm(`确认要${text}${row.productName}产品吗？`).then(() => {
        if (row.publishState === 1) { deployProduct(row.id) }
        if (row.publishState === 0) { undeployProduct(row.id) }
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(() => {
        row.publishState = row.publishState === 1 ? 0 : 1;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.id = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleDetails(row) {
      // 隐藏主页面显示详情页
      this.$store.commit("PRODUCT_DETAILED_PAGE_VISIBLE", true);
      // 传递数据给详情页面
      let productData = JSON.parse(JSON.stringify(row));
      this.$store.commit("PRODUCT_DATA", productData);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品ID为"' + ids + '"的数据项？').then(function() {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.productAddEdit.handleAdd();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.$refs.productAddEdit.handleUpdate(id);
    },
    /** 转换品类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        label: node.categoryName
      };
    },

    /** 查询品类下拉树结构 */
    getTreeselect() {
      listCategory().then(({ data }) => {
        if (!data) {
          return;
        }
        this.categoryOptions = this.handleTree(data);
      });
    },

  }
};
</script>
